/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.gt.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.gt.entity.GtCompany;
import com.thinkgem.jeesite.modules.gt.entity.GtCompanyPeople;
import com.thinkgem.jeesite.modules.gt.entity.GtForestPeople;
import com.thinkgem.jeesite.modules.gt.service.GtCompanyPeopleService;
import com.thinkgem.jeesite.modules.gt.service.GtCompanyService;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.service.AreaService;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;

/**
 * 企社信息Controller
 * @author zad
 * @version 2018-03-26
 */
@Controller
@RequestMapping(value = "${frontPath}/gt/gtCompany")
public class GtCompanyController extends BaseController {

	@Autowired
	private GtCompanyService gtCompanyService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private GtCompanyPeopleService gtCompanyPeopleService;
	
	
	@ModelAttribute
	public GtCompany get(@RequestParam(required=false) String id) {
		GtCompany entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = gtCompanyService.get(id);
		}
		if (entity == null){
			entity = new GtCompany();
		}
		return entity;
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(GtCompany gtCompany,String menuId, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		this.areaService.fetchRegions(model);
		if(null == gtCompany.getArea() || StringUtils.isBlank(gtCompany.getArea().getCode()))
		{
			Area area = UserUtils.getUser().getArea();
			gtCompany.setArea(area);
		}
		
		Page<GtCompany> page = gtCompanyService.findPage(new Page<GtCompany>(request, response), gtCompany); 
		model.addAttribute("page", page);
		
		model.addAttribute("gtCompany", gtCompany);
		model.addAttribute("menuId", menuId);
		
		return "modules/gt/basic/gtCompanyList";
	}

	/**
     * 导出文件
     */
    @RequestMapping("downLoad")
    public void downLoad(String areaId,GtCompanyPeople gtCompanyPeople,String timeStamp, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException{
    	Area area = null;
    	if("undefined".equals(areaId))
    	{
    		areaId = "";
    	}
    	if(!StringUtils.isEmpty(areaId))
		{
			area = this.areaService.get(areaId);
		}
    	
    	response.setCharacterEncoding("utf-8");
    	String fileName = UserUtils.getUser().getArea().getName() + Global.getConfig("exportCompanyFileName");
    	
    	if(null != area)
    	{
    		fileName = area.getName() + Global.getConfig("exportCompanyFileName");
    	}
    	
    	fileName += DateUtils.getDate();
        // fileName = URLEncoder.encode(fileName, "UTF-8");
    	
    	// response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
        
        SXSSFWorkbook wb = new SXSSFWorkbook(-1);
        // turn off auto-flushing and accumulate all rows in memory  
        wb.setCompressTempFiles(true); //使用gzip压缩,减小空间占用  
        Sheet sh = wb.createSheet("龙头企业（合作社）扶贫信息");
        OutputStream out = new BufferedOutputStream(response.getOutputStream());
        try { //从数据库中得到结果  
        	
        	
        	
        	//9c65bfefb542491a89dc2aa8723e60ff
        	GtCompany gtCompany = new GtCompany();
        	if(null == gtCompany.getArea() || StringUtils.isBlank(gtCompany.getArea().getCode()))
    		{
        		if(StringUtils.isEmpty(areaId))
        		{
	    			area = UserUtils.getUser().getArea();
	    			gtCompany.setArea(area);
        		}
        		else
        		{
        			gtCompany.setArea(area);
        		}
    		}
        	gtCompanyPeople.setCompany(gtCompany);
        	
        	Page<GtCompanyPeople> page = new Page<GtCompanyPeople>();
        	page.setOrderBy("hezuoshe");
        	gtCompanyPeople.setPage(page);
        	
        	
        	
            List<GtCompanyPeople> list = this.gtCompanyPeopleService.findList(gtCompanyPeople);
            
            if(null == list || list.size() < 1)
            {
	            sh.setColumnWidth(0, 50 * 256);
	        	Row rowHeader = sh.createRow(0);
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("信息提示");
	            
	            Row row = sh.createRow(1);
	            Cell cell = row.createCell(0);  
	            cell.setCellValue("没有找到相关条件的数据。");  
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
            }else
            {
	            
	            //设置每一列的宽度,注意 要乘以256,因为1代表excel中一个字符的1/256的宽度  
	            sh.setColumnWidth(0, 5 * 256);
	            sh.setColumnWidth(1, 30 * 256);
	            sh.setColumnWidth(2, 40 * 256);
	            sh.setColumnWidth(3, 10 * 256);
	            sh.setColumnWidth(4, 15 * 256);
	            sh.setColumnWidth(5, 9 * 256);
	            sh.setColumnWidth(6, 30 * 256);
	            sh.setColumnWidth(7, 22 * 256);
	            sh.setColumnWidth(8, 30 * 256);
	            /*sh.setColumnWidth(8, 10 * 256);*/
	            sh.setColumnWidth(9, 10 * 256);
	            Row rowHeader = sh.createRow(0);
	            /*CellStyle headerStyle = rowHeader.getRowStyle();
	            headerStyle.setAlignment(CellStyle.ALIGN_CENTER);*/
	            Cell cellHeader = rowHeader.createCell(0);
	            cellHeader.setCellValue("序号");
	            cellHeader = rowHeader.createCell(1);
	            cellHeader.setCellValue("所属单位");
	            cellHeader = rowHeader.createCell(2);
	            cellHeader.setCellValue("企业（合作社）名称");
	            cellHeader = rowHeader.createCell(3);
	            cellHeader.setCellValue("联系人");
	            cellHeader = rowHeader.createCell(4);
	            cellHeader.setCellValue("联系方式");
	            cellHeader = rowHeader.createCell(5);
	            cellHeader.setCellValue("姓名");
	            cellHeader = rowHeader.createCell(6);
	            cellHeader.setCellValue("家庭住址");
	            cellHeader = rowHeader.createCell(7);
	            cellHeader.setCellValue("身份证号");
	            cellHeader = rowHeader.createCell(8);
	            cellHeader.setCellValue("方式");
	            /*cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("金额");*/
	            cellHeader = rowHeader.createCell(9);
	            cellHeader.setCellValue("备注");
	            
	            // 只取5000条数据
	            /*if(null != list && list.size() > Constant.Join.JOIN_EXPORT_MOST_ROWS)
	            {
	            	list.subList(Constant.Join.JOIN_EXPORT_MOST_ROWS, list.size()).clear();
	            }*/
	            
	            // 记录本次龙头企业（合作社）信息id，用于区分是不是同一个龙头企业（合作社）信息
	            String nowCompanyId = null;
	            // 本次龙头企业（合作社）信息合并单元格开始行数，默认为0；
	            int nowCompanyBeginRow = 0;
	            // 序号
	            int seq = 1;
	            int size = list.size();
	            for(int i = 0; i < size; i++) {
	            	
	            	// 当前龙头企业（合作社）
	            	GtCompanyPeople companyPeople = list.get(i);
	            	
	            	// 下一个龙头企业（合作社）
	            	GtCompanyPeople companyPeopleNext = null;
	            	// 存在下一个，则获取下一个，用于查看本次龙头企业（合作社）与下一个龙头企业（合作社）是否是同一个龙头企业（合作社）
	            	if(i+1 < size)
	            	{
	            		companyPeopleNext = list.get(i+1);
	            	}
	            	else
	            	{
	            		companyPeopleNext = null;
	            	}
	            	
	            	Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	            	
	            	// 第一次初始化本次龙头企业（合作社）id
	            	if(i == 0)
	            	{
	            		nowCompanyId = companyPeople.getCompany().getId();
	            		nowCompanyBeginRow = 0;
	            		cell.setCellValue(seq);
	            		cell = row.createCell(1);
		                cell.setCellValue(companyPeople.getCompany().getArea().getName());  
		                cell = row.createCell(2);
		                cell.setCellValue(companyPeople.getCompany().getName());  
		                cell = row.createCell(3);
		                cell.setCellValue(companyPeople.getCompany().getCreateBy().getOperName());
		                cell = row.createCell(4);
		                cell.setCellValue(companyPeople.getCompany().getCreateBy().getMobile());
	            	}
	            	// 判断
	            	else
	            	{
	            		// 上一个龙头企业（合作社）信息id
	            		String lastCompanyId = list.get(i-1).getCompany().getId();
	            		// 本次龙头企业（合作社）信息id和上次龙头企业（合作社）信息id不一致，则说明本次是新的龙头企业（合作社）开始
	            		if(!lastCompanyId.equals(companyPeople.getCompany().getId()))
	            		{
	            			nowCompanyBeginRow = i;
	            			seq ++;
	            			
	            			cell.setCellValue(seq);
	            			cell = row.createCell(1);
			                cell.setCellValue(companyPeople.getCompany().getArea().getName());  
	    	                cell = row.createCell(2);
	    	                cell.setCellValue(companyPeople.getCompany().getName());  
	    	                cell = row.createCell(3);
	    	                cell.setCellValue(companyPeople.getCompany().getCreateBy().getOperName());
	    	                cell = row.createCell(4);
	    	                cell.setCellValue(companyPeople.getCompany().getCreateBy().getMobile());
	            		}
	            		
	            	}
	            	
	            	
	                /*Row row = sh.createRow(i+1);
	                Cell cell = row.createCell(0);  
	                cell.setCellValue(seq);
	                cell = row.createCell(1);
	                cell.setCellValue(companyPeople.getCompany().getName());  
	                cell = row.createCell(2);
	                cell.setCellValue(companyPeople.getCompany().getCreateBy().getOperName());
	                cell = row.createCell(3);
	                cell.setCellValue(companyPeople.getCompany().getCreateBy().getMobile());*/
	                
	                
	                cell = row.createCell(5);
	                cell.setCellValue(companyPeople.getName());
	                
	                cell = row.createCell(6);
	                // cell.setCellValue(DictUtils.getDictLabel(forestPeople.getJoinType(), "dictType", null));
	                cell.setCellValue(companyPeople.getAddress());
	                
	                cell = row.createCell(7);
	                cell.setCellValue(companyPeople.getIdcard());
	                cell = row.createCell(8);
	                /*cell.setCellValue(DictUtils.getDictLabel(companyPeople.getHelpType(), "gt_help_type", null) 
	                		+ ("o".equals(companyPeople.getHelpType())?"(" + companyPeople.getHelpOther() + ")":""));*/
	                
	                String helpType = companyPeople.getHelpType();
	                if(helpType.length() < 2){
	                	cell.setCellValue(DictUtils.getDictLabel(helpType, "gt_help_type", null) 
	                		+ ("o".equals(helpType)?"(" + companyPeople.getHelpOther() + ")":""));
	                }
	                else
	                {
	                	String helpVal = "";
	                	String [] helpArr = helpType.split(",");
	                	for(String help:helpArr)
	                	{
	                		if(StringUtils.isEmpty(help))
	                		{
	                			continue;
	                		}
	                		
	                		helpVal += DictUtils.getDictLabel(help, "gt_help_type", null) + " ";
	                		if("o".equals(help))
	                		{
	                			helpVal += "(" + companyPeople.getHelpOther() + ")";
	                		}
	                	}
	                	cell.setCellValue(helpVal);
	                	
	                }
	                
	                
	                /*cell = row.createCell(9);  
	                cell.setCellValue(null == companyPeople.getMoney()?"0":String.valueOf(companyPeople.getMoney()));*/
	                cell = row.createCell(9);  
	                cell.setCellValue(companyPeople.getRemarks());
	                
	                
	                // 对比本次龙头企业（合作社）和下一个龙头企业（合作社）是否是同一个，
	            	if(i > 0)
	            	{
	            		nowCompanyId = companyPeople.getCompany().getId();
	            		// 没有下一个龙头企业（合作社）信息或者下一个龙头企业（合作社）信息和本次龙头企业（合作社）信息不是同一个，则开始合并单元格
	            		if(null == companyPeopleNext || !nowCompanyId.equals(companyPeopleNext.getCompany().getId()))
	            		{
	            			for(int col = 0; col < 5; col ++)
	            			{
		            			// 合并单元格，开始行为 nowForestBeginRow + 1，结束行为i + 1(+1是因为第0行为标题)
		            			CellRangeAddress cellAddr = new CellRangeAddress(nowCompanyBeginRow + 1, i + 1, col, col);
		            			sh.addMergedRegion(cellAddr);
	            			}
	            		}
	            	}
	                
	      
	                /*if(i > 0 && (i % 1000 == 0)) {  
	                    ((SXSSFSheet) sh).flushRows();  
	                } */
	            }
	            
	            ((SXSSFSheet) sh).flushRows();
	            
	            CookieUtils.rememberCookieToken(timeStamp,request,response);
	            //统一写出方法
	            FileUtils.writeWb(wb,out);
	            
            }
        } catch(Exception e) {
        	sh.setColumnWidth(0, 50 * 256);
        	Row rowHeader = sh.createRow(0);
            Cell cellHeader = rowHeader.createCell(0);
            cellHeader.setCellValue("信息提示");
            
            Row row = sh.createRow(1);
            Cell cell = row.createCell(0);  
            cell.setCellValue("导出失败，请联系管理员。错误信息：" + e.getMessage());  
            
            e.printStackTrace();
            ((SXSSFSheet) sh).flushRows();
            
            CookieUtils.rememberCookieToken(timeStamp,request,response);
            //统一写出方法
            FileUtils.writeWb(wb,out);
        }  
     // 保存日志
     request.setAttribute("title", "用户" + UserUtils.getUser().getLoginName() + "导出了文件：" + fileName);
    }
	
	// 企社扶贫人列表
	@RequestMapping(value = {"listCompanyPeople"})
	public String listCompanyPeople(GtCompanyPeople gtCompanyPeople, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		
		Page<GtCompanyPeople> page = gtCompanyPeopleService.findPage(new Page<GtCompanyPeople>(request, response), gtCompanyPeople); 
		model.addAttribute("page", page);
		gtCompanyPeople.setCompany(this.gtCompanyService.get(gtCompanyPeople.getCompany().getId()));
		model.addAttribute("gtCompanyPeople", gtCompanyPeople);
		
		return "modules/gt/basic/gtCompanyPeopleList";
	}
	
	@RequestMapping(value = "form")
	public String form(GtCompany gtCompany, Model model) {
		
		this.areaService.fetchRegions(model);
		
		model.addAttribute("gtCompany", gtCompany);
		return "modules/gt/basic/gtCompanyForm";
	}

	@RequestMapping(value = "formCompanyPeople")
	public String formCompanyPeople(GtCompanyPeople gtCompanyPeople, Model model) {
		
		gtCompanyPeople.setCompany(this.gtCompanyService.get(gtCompanyPeople.getCompany().getId()));
		
		List<Dict> helpTypes = DictUtils.getDictList("gt_help_type");
		model.addAttribute("helpTypes", helpTypes);
		
		// 修改时，查询相关信息
		if(StringUtils.isNotBlank(gtCompanyPeople.getId()))
		{
			// 记住菜单id
			String menuId = gtCompanyPeople.getMenuId();
			gtCompanyPeople = this.gtCompanyPeopleService.get(gtCompanyPeople.getId());
			gtCompanyPeople.setMenuId(menuId);
		}
		
		model.addAttribute("gtCompanyPeople", gtCompanyPeople);
		return "modules/gt/basic/gtCompanyPeopleForm";
	}
	
	@RequestMapping(value = "save")
	public String save(GtCompany gtCompany,String oper,HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, gtCompany)){
			return form(gtCompany, model);
		}
		
		
		
		if(StringUtils.isBlank(gtCompany.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加龙头企业（合作社）:" + gtCompany.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改龙头企业（合作社）:" + gtCompany.getName());
		}

		

		
		//根据企社名称来判断是否是合作社（含合作社名称的为合作社）type：1，龙头企业；2，合作社
		String name = gtCompany.getName();
		// 名称为空或者名称中不含合作社，则为龙头企业，否则为合作社
		if(StringUtils.isBlank(name) || name.indexOf("合作社") < 0)
		{
			gtCompany.setType(Constant.Company.COMPANY_TYPE_COMPANY);
		}
		else
		{
			gtCompany.setType(Constant.Company.COMPANY_TYPE_COOP);
		}
		
		gtCompanyService.save(gtCompany);
		addMessage(redirectAttributes, "保存龙头企业（合作社）信息成功");
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtCompany/form?menuId=" + gtCompany.getMenuId();
		}
				
		return "redirect:"+super.frontPath+"/gt/gtCompany?menuId=" + gtCompany.getMenuId();
	}
	
	@RequestMapping(value = "saveCompanyPeople")
	public String saveCompanyPeople(GtCompanyPeople gtCompanyPeople,HttpServletRequest request, HttpServletResponse response, String oper, Model model, RedirectAttributes redirectAttributes) {
		

		
		if(StringUtils.isBlank(gtCompanyPeople.getId()))
		{
			// 日志标题
			request.setAttribute("title", "添加龙头企业（合作社）贫困人:" + gtCompanyPeople.getName());
		}else
		{
			// 日志标题
			request.setAttribute("title", "修改龙头企业（合作社）贫困人:" + gtCompanyPeople.getName());
		}
		
		
		
		gtCompanyPeopleService.save(gtCompanyPeople);
		addMessage(redirectAttributes, "保存龙头企业（合作社）贫困人口信息成功");
		
		// model.addAttribute("gtCompanyPeople", gtCompanyPeople);
		// redirectAttributes.addFlashAttribute("gtCompanyPeople", gtCompanyPeople);
		
		// 保存后继续到添加页面
		if("form".equals(oper))
		{
			return "redirect:"+super.frontPath+"/gt/gtCompany/formCompanyPeople/?company.id=" + gtCompanyPeople.getCompany().getId() + "&menuId=" + gtCompanyPeople.getMenuId();
		}
		else
		{
			return "redirect:"+super.frontPath+"/gt/gtCompany/listCompanyPeople/?company.id=" + gtCompanyPeople.getCompany().getId() + "&menuId=" + gtCompanyPeople.getMenuId();
		}
	}
	
	@RequestMapping(value = "delete")
	public String delete(GtCompany gtCompany,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		
		this.gtCompanyPeopleService.deleteByCompanyId(gtCompany.getId());
		
		gtCompanyService.delete(gtCompany);
		addMessage(redirectAttributes, "删除龙头企业（合作社）信息成功");
		
		// 日志标题
		request.setAttribute("title", "删除龙头企业（合作社）[及下级贫困人]:" + gtCompany.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtCompany?menuId=" + gtCompany.getMenuId();
	}
	
	@RequestMapping(value = "deleteCompanyPeople")
	public String deleteCompanyPeople(GtCompanyPeople gtCompanyPeople,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		this.gtCompanyPeopleService.delete(gtCompanyPeople);
		addMessage(redirectAttributes, "删除龙头企业（合作社）贫困人口信息成功");
		
		
		// 日志标题
		request.setAttribute("title", "删除龙头企业（合作社）贫困人:" + gtCompanyPeople.getId());
		
		
		return "redirect:"+super.frontPath+"/gt/gtCompany/listCompanyPeople?company.id=" + gtCompanyPeople.getCompany().getId() + "&menuId=" + gtCompanyPeople.getMenuId();
	}

}